package com.greenold.commen.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.greenold.check.domain.Dto.PendingTasksDto;
import com.greenold.check.domain.PendingTasks;
import com.greenold.common.core.domain.entity.SysUser;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.system.mapper.SysUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.util.CollectionUtil;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WorkFlowServie {
    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 启动流程实例并（可选）自动完成首节点
     *
     * @param businessId         业务主键（如入住申请id）
     * @param user               当前登录用户（发起人）
     * @param processDefinitionKey 流程定义key（例如 "checkIn"）
     * @param variables          流程变量（assignee、title、type等）
     * @param isAutoCompleteFirstTask 是否自动完成首节点
     * @return processInstanceId 流程实例ID
     */
    public String startProcess(String businessId, SysUser user, String processDefinitionKey,
                               Map<String, Object> variables, boolean isAutoCompleteFirstTask) {
        try {
            // 构造 businessKey：流程key:业务id
            String businessKey = processDefinitionKey + ":" + businessId;

            // 1. 启动流程实例
            ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
            String processInstanceId = instance.getId();

            // 2. 查询当前用户的任务列表
            List<Task> taskList = taskService.createTaskQuery()
                    .processDefinitionKey(processDefinitionKey)
                    .processInstanceBusinessKey(businessKey)
                    .taskAssignee(user.getUserId().toString())
                    .list();

            // 3. 自动完成首节点任务（FormKey = "0" 或第一个节点）
            if (!CollectionUtil.isEmpty(taskList) && isAutoCompleteFirstTask) {
                List<Task> firstTasks = taskList.stream()
                        .filter(t -> "0".equals(t.getFormKey()) || "0.".equals(t.getFormKey()))
                        .collect(Collectors.toList());

                for (Task task : firstTasks) {
                    Map<String, Object> vars = new HashMap<>();
                    vars.put( "processBusinessId", processInstanceId);
                    vars.put("status", 1);
//                    vars.put("processApplyStatus", 1); //1 表示申请中
                    vars.put("ops", "1");
                    System.out.println("变量ops类型：" + vars.get("ops").getClass());
                    taskService.complete(task.getId(), vars);
                }
            }

            return processInstanceId;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("流程启动失败：" + e.getMessage(), e);
        }
    }

    /**
     * 获取流程当前的下一个审批人
     *
     * @param processDefinitionKey 流程定义key
     * @param businessKey          businessKey
     * @return 下一审批人ID（字符串）
     */
    public SysUser getNextAssignee(String processInstanceId) {
        Task nextTask = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        if (nextTask == null || nextTask.getAssignee() == null) {
            return null;
        }
        return sysUserMapper.selectUserById(Long.valueOf(nextTask.getAssignee()));
    }
    //获取下一个任务
    public Task getNextTask(String processInstanceId) {
        return taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    /**
     * 完成当前任务（可指定操作类型）
     *
     * @param taskId 当前任务ID
     * @param userId 当前处理人
     * @param ops    操作类型（1同意、2拒绝、3驳回）
     */
    public void completeTask(String taskId, String ops) {
        Task currentTask = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (currentTask == null) return;

        String processInstanceId = currentTask.getProcessInstanceId();
        System.out.println("=== 流程调试信息 ===");
        System.out.println("当前任务: " + currentTask.getName() + " (ID: " + taskId + ")");
        System.out.println("流程实例ID: " + processInstanceId);
        System.out.println("操作参数 ops: " + ops);
        Map<String, Object> variables = new HashMap<>();
        variables.put("ops", ops);
        variables.put("finishTime", new Date());
        taskService.setVariables(taskId, variables);
        // 关键修改：查询当前流程实例的所有活跃任务，手动过滤当前任务
        List<Task> allActiveTasks = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .list(); // 获取该流程实例的所有活跃任务
        // 过滤掉当前任务，判断是否还有其他任务
        boolean hasNextTask = allActiveTasks.stream()
                .anyMatch(task -> !taskId.equals(task.getId())); // 存在非当前任务 → 流程未结束
        if (!hasNextTask) {
            // 无其他任务，预判流程即将结束，设置最终 status
            if ("1".equals(ops) || "2".equals(ops)) {
                variables.put("status", 2); // 已完成
            } else {
                variables.put("status", 3); // 已关闭
            }
        } else {
            // 有其他任务，流程未结束，保持临时状态
            variables.put("status", 1); // 申请中
        }
        // 完成任务时传入所有变量，避免后续操作已结束的实例
        taskService.complete(taskId, variables);
        // 移除原有的 runtimeService.setVariables 逻辑，彻底避免报错
    }
    public List<PendingTasks> getMyTaskList(PendingTasksDto pendingTasksDto) {
        Long currentUserId  = SecurityUtils.getUserId();
        HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery();
        taskQuery.taskAssignee(currentUserId.toString());
        // 已完成 / 未完成
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getIsHandle())) {
            if (pendingTasksDto.getIsHandle() == 1) {
                taskQuery.finished();
            } else {
                taskQuery.unfinished();
            }
        }

        // 我的申请 or 待办任务
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getReqType())) {
            if (Integer.valueOf(1).equals(pendingTasksDto.getReqType())) {
                taskQuery = taskQuery.taskNameLike("%申请%");
            } else if (Integer.valueOf(0).equals(pendingTasksDto.getReqType())){
                taskQuery = taskQuery.taskNameLike("%处理%");
            }
        }

        // 时间范围
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getStartTime()) && ObjectUtil.isNotEmpty(pendingTasksDto.getEndTime())) {
            taskQuery.taskCreatedAfter(pendingTasksDto.getStartTime())
                    .taskCreatedBefore(pendingTasksDto.getEndTime());
        }


        if (ObjectUtil.isNotEmpty(pendingTasksDto.getType())) {
            taskQuery.processVariableValueEquals("processType", pendingTasksDto.getType());
        }

        // 单据code (String 类型，原样传)
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getCode())) {
            taskQuery.processVariableValueEquals("processCode", pendingTasksDto.getCode());
        }

        // 流程状态 (Integer -> String)
//        if (ObjectUtil.isNotEmpty(pendingTasksDto.getStatus())) {
//            taskQuery.processVariableValueEquals("status", pendingTasksDto.getStatus());
//        }

        // 7. 申请人过滤（新增，匹配申请人姓名）
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getApplicat())) {
            taskQuery.processVariableValueLike("assignee0Name", "%" + pendingTasksDto.getApplicat() + "%");
        }
        List<HistoricTaskInstance> list = taskQuery
                .includeProcessVariables()
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();
        if (ObjectUtil.isNotEmpty(pendingTasksDto.getStatus())) {
            if (pendingTasksDto.getStatus() == 1) {
                list = list.stream()
                        .filter(task -> task.getEndTime() == null)
                        .collect(Collectors.toList());
            } else if (pendingTasksDto.getStatus() == 2) {
                list = list.stream()
                        .filter(task -> task.getEndTime() != null)
                        .collect(Collectors.toList());
            }
        }
        List<PendingTasks> pendingTasksList = new ArrayList<>();
        for (HistoricTaskInstance task : list) {
            System.err.println( task);

            Map<String, Object> processVariables = task.getProcessVariables();
            PendingTasks pendingTasks = new PendingTasks();
            pendingTasks.setId(task.getId());
            pendingTasks.setProcessInstanceId(task.getProcessInstanceId());

            // 安全取值
            pendingTasks.setCode(processVariables.getOrDefault("processCode", "").toString());
            pendingTasks.setType(processVariables.get("processType") != null ?
                    Integer.parseInt(processVariables.get("processType").toString()) : null);
            pendingTasks.setTitle(processVariables.getOrDefault("processTitle", "").toString());
            pendingTasks.setApplicat(processVariables.getOrDefault("assignee0Name", "").toString());
//            pendingTasks.setStatus(processVariables.get("status") != null ?
//                    Integer.parseInt(processVariables.get("status").toString()) : null);
            pendingTasks.setStatus(task.getEndTime()==null?1:2);
            pendingTasks.setAssigneeId(task.getAssignee() != null ? Long.valueOf(task.getAssignee()) : null);
            pendingTasks.setTaskName(task.getName());
            pendingTasks.setFinishTime(task.getEndTime());
            Object applicationTimeObj = processVariables.get("applicationTime");
            if (applicationTimeObj instanceof Date) {
                // 直接强转Date类型（避免字符串解析错误）
                pendingTasks.setApplicationTime((Date) applicationTimeObj);
            } else if (applicationTimeObj instanceof String) {
                // 兼容字符串格式（若存在）
                try {
                    pendingTasks.setApplicationTime(DateUtil.parse((String) applicationTimeObj));
                } catch (Exception e) {
                    pendingTasks.setApplicationTime(null);
                }
            } else {
                // 变量不存在时，用任务创建时间兜底（业务上申请时间≈任务创建时间）
                pendingTasks.setApplicationTime(task.getCreateTime());
            }
            pendingTasks.setStepNo(task.getFormKey() != null ? Integer.parseInt(task.getFormKey()) : null);

            pendingTasksList.add(pendingTasks);
        }

        return pendingTasksList;
    }

    /*
    * 历史任务查询
    * */
    public List<Map<String,Object>> getHistoryTaskList(String bussinessId){
        List<Map<String,Object>> result = new ArrayList<>();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(bussinessId)
                .orderByTaskCreateTime()
                .asc()
                .list();
        for(HistoricTaskInstance task : list)
        {    Map<String,Object> map = new HashMap<>();
             SysUser user = sysUserMapper.selectUserById(Long.valueOf(task.getAssignee()));
             map.put("userInfo", user);
             map.put("taskInfo", task);
            result.add(map);
        }
        return result;
    }
}

